package edu.zju.gis.dbfg.model.scala

import edu.zju.gis.dbfg.model.base.GeoItem
import geotrellis.proj4.LatLng
import geotrellis.raster.io.geotiff.GeoTiff
import geotrellis.raster.rasterize.Rasterizer
import geotrellis.raster.rasterize.Rasterizer.foreachCellByGeometry
import geotrellis.raster.{ArrayTile,NODATA, RasterExtent, Tile, _}
import geotrellis.vector.Extent
import org.apache.spark.Partitioner

import scala.collection.JavaConverters._

/**
 * @author Hu
 * @date 2019/10/31
 **/
object MRasterizer2{

  def getOptions: Rasterizer.Options = Rasterizer.Options.DEFAULT

  def getPartitioner: Option[Partitioner] = None

  def getRasterExtent(extent: Extent, xresolution: Double, yresolution: Double): RasterExtent = {
    val cols = ((extent.xmax-extent.xmin)/xresolution).toInt + 1
    val rows = ((extent.ymax-extent.ymin)/yresolution).toInt + 1
    // RasterExtent(extent, ((extent.xmax-extent.xmin)*10000).toInt, ((extent.ymax-extent.ymin)*10000).toInt)
    RasterExtent(extent, cols, rows)
  }

  def rasterizeWithValue(jFeatures:java.util.List[GeoItem], rasterExtent: RasterExtent): MultibandTile = {
    val features = jFeatures.asScala
    val cols = rasterExtent.cols
    val arrayCC = Array.ofDim[Int](rasterExtent.cols * rasterExtent.rows).fill(NODATA)
    val arrayID = Array.ofDim[Int](rasterExtent.cols * rasterExtent.rows).fill(NODATA)
    for(feature <- features){
      foreachCellByGeometry(feature.getGeometry, rasterExtent){
        (col, row)=>
          arrayCC(row * cols + col) = feature.getProp.getOrDefault("CC", "").toString.toInt
          arrayID(row * cols + col) = feature.getFid.toInt
      }}
    val tileCC=ArrayTile(arrayCC, rasterExtent.cols, rasterExtent.rows)
    val tileID = ArrayTile(arrayID, rasterExtent.cols, rasterExtent.rows)
    ArrayMultibandTile(Array(tileCC,tileID))
  }

  def write(tile: MultibandTile, extent: Extent, outpath: String) = {
    GeoTiff(tile, extent, LatLng).write(outpath)
  }

}
